<!-- 停车场信息 -->
<template>
  <div class="pad-content-box">
    <div class="t-right padding-top-15">
      <el-button type="primary" size="mini" v-if="!btnStatus && model.projectStatus == 1" @click="approveSubmit">批量提交</el-button>
      <el-button type="primary" size="mini" v-if="!btnStatus && model.projectStatus == 2" @click="approveFn">批量提审</el-button>
      <el-button type="primary" size="mini" @click="draftFn" v-if="isPageEdit">
        {{ btnStatus ? '未生效版本' : '已生效版本' }}
      </el-button>
    </div>

    <el-collapse v-model="activeNames" class="margin-top-15">
      <!-- 地下停车场和立体停车楼 -->
      <el-collapse-item name="1">
        <template slot="title">
          <div class="flex justify-between align-centers" style="width: 100%">
            <div>
              <span class="font-size-16 padding-left-10 font-weight-700">地下停车场和立体停车楼</span>
            </div>
            <div class="margin-right-10">
              <el-button size="mini" type="primary" plain @click.stop="addPark('under')" v-if="!btnStatus">添加停车场</el-button>
            </div>
          </div>
        </template>

        <template v-if="underFloorParkList.length > 0">
          <div v-for="(item, index) in underFloorParkList" :key="index" class="full-box relative-box" :class="index < underFloorParkList.length - 1 ? 'margin-bottom-20 border-bottom-F2F2F2' : ''">
            <form-common v-if="underFiledList[index] && underFiledList[index].length > 0" :filed-list="underFiledList[index]" :ref="`underFloorform${index}`" @typeBtnClick="typeBtnClick"></form-common>
            <div class="park-btn-box">
              <el-button class="f-right" plain type="danger" size="mini" @click="deleteFn(item)" v-if="!btnStatus">删除</el-button>
              <el-button class="f-right margin-right-10" plain type="primary" size="mini" @click="editFn(item, 'under', 'underFloorform' + index)" v-if="!btnStatus">编辑</el-button>
            </div>
          </div>
        </template>
        <el-empty v-else description="暂无停车场"></el-empty>
      </el-collapse-item>

      <!-- 地面停车场 -->
      <el-collapse-item name="2">
        <template slot="title">
          <div class="flex justify-between align-centers" style="width: 100%">
            <div>
              <span class="font-size-16 padding-left-10 font-weight-700">地面停车场</span>
            </div>
            <div class="margin-right-10">
              <el-button size="mini" type="primary" plain @click.stop="addPark('on')" v-if="!btnStatus">添加停车场</el-button>
            </div>
          </div>
        </template>

        <template v-if="onFloorParkList.length > 0">
          <div v-for="(item, index) in onFloorParkList" :key="index" class="full-box relative-box" :class="index < onFloorParkList.length - 1 ? 'margin-bottom-20 border-bottom-F2F2F2' : ''">
            <form-common v-if="onFiledList[index] && onFiledList[index].length > 0" :filed-list="onFiledList[index]" :ref="`onFloorform${index}`" @typeBtnClick="typeBtnClick"></form-common>
            <div class="park-btn-box">
              <el-button class="f-right" plain type="danger" size="mini" @click="deleteFn(item)" v-if="!btnStatus">删除</el-button>
              <el-button class="f-right margin-right-10" plain type="primary" size="mini" @click="editFn(item, 'on', 'onFloorform' + index)" v-if="!btnStatus">编辑</el-button>
            </div>
          </div>
        </template>
        <el-empty v-else description="暂无停车场"></el-empty>
      </el-collapse-item>
    </el-collapse>

    <!-- 停车场dialog -->
    <el-dialog title="停车场" :visible.sync="dialogShow" width="80%" :close-on-click-modal="false" :close-on-press-escape="false">
      <form-common v-if="parkType == 'under' && underFloorParkFiledList.length > 0" :filed-list="underFloorParkFiledList" ref="parkForm" @selectChange="selectChange"></form-common>
      <form-common v-if="parkType == 'on' && onFloorParkFiledList.length > 0" :filed-list="onFloorParkFiledList" ref="parkForm"></form-common>

      <div class="flex margin-bottom-20">
        <p class="left-lable font-size-16 padding-left-right-10 margin-top-5 font-weight-400 color-333333" style="width: 150px">停车场图片</p>
        <el-upload action accept=".xlsx,.xls,.csv,.png,.jpg,.Png,.Jpg" :show-file-list="false" :http-request="event => beforeupload(event.file)" class="avatar-uploader">
          <img v-if="parkImg" :src="parkImg" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>

      <div class="flex margin-bottom-20">
        <p class="left-lable font-size-16 padding-left-right-10 margin-top-5 font-weight-400 color-333333" style="width: 150px">合同附件</p>
        <uploadFile :is-multiple="true" :limit="10" filed-name="file" :max-size="20" accept-file-type=".png,.jpg,.Png,.Jpg" :file-list="fileList" @handleSuccess="handleSuccess" file-url-name="fileUrl" file-txt-name="fileTitle"> </uploadFile>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogShow = false">取消</el-button>
        <el-button size="small" type="primary" @click="confirmAddPark">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="附件" :visible.sync="fileDialog" width="800px" :close-on-click-modal="false" :close-on-press-escape="false">
      <div v-for="(item, index) in fileList" :key="index" class="margin-bottom-15">
        附件{{ index + 1 }}：<el-link type="primary" @click="uploadLoad(item.fileUrl)">{{ item.fileTitle }}</el-link>
      </div>
    </el-dialog>

    <!-- <approvePark ref="parkDialog" :work-id="workId"></approvePark> -->

    <el-image-viewer v-if="imgViewerVisible" :on-close="closeImgViewer" :url-list="imgList" />
  </div>
</template>
<script>
  import { onFloorParkFiledList, underFloorParkFiledList } from '../form.js';
  import formCommon from '@g/components/form/formCommon.vue';
  import { uploadPhoto } from '@/api';
  import approvePark from '../modules/dialog/approvePark';
  import uploadFile from '../modules/upload.vue';
  import projectInfoApi from '../../../api/projectInfo';
  import { requestTips, askDialog } from '../../../assets/util';

  export default {
    data() {
      return {
        activeNames: ['1', '2'],
        onFloorParkFiledList: [],
        underFloorParkFiledList: [],
        onFiledList: [],
        underFiledList: [],
        dialogShow: false,
        parkType: 'under', //0地面停车场,1地下停车场
        onFloorParkList: [],
        underFloorParkList: [],
        fileList: [],
        parkImg: '',
        fileDialog: false,
        infoKey: '', //编辑时候才有的主键
        btnStatus: true,
        areaList: [],
        model: {},
        imgViewerVisible: false,
        imgList: [],
        projectKey: this.$route.query.projectKey || localStorage.getItem('projectKey'),
      };
    },
    computed: {
      isPageEdit() {
        return !this.$route.query.taskId;
      },
    },
    async mounted() {
      this.getProjectInfo();
      await this.getBuilding();
      this.initPage();
      this.getInfo();
    },

    methods: {
      //楼栋
      async getBuilding() {
        let res = await projectInfoApi.apiAllBuildList({
          projectKey: this.$route.query.projectKey,
        });
        underFloorParkFiledList.forEach(item => {
          if (item.bindFieldName == 'buildingKey') {
            item.optionList = res.rows;
          }
        });
      },
      //初始化页面配置
      initPage() {
        this.onFloorParkFiledList = JSON.parse(JSON.stringify(onFloorParkFiledList));
        this.underFloorParkFiledList = JSON.parse(JSON.stringify(underFloorParkFiledList));
        this.onFloorParkFiledList.splice(-2, 2);
        this.underFloorParkFiledList.splice(-2, 2);
      },
      //初始化filed只读
      initFormReadOnly(list) {
        list.forEach(item => {
          item.isReadOnly = true;
          item.isRequired = false;
          if (item.type == 'select' || item.type == 'date' || item.type == 'radio' || item.type == 'checkbox') {
            item.isDisabled = true;
          }
        });
      },
      //页面数据源 parkType 0地上 1地下
      async getInfo(type) {
        let apiName = type == 'draft' ? 'apiParkDraft' : 'apiParkList';
        let param = {
          projectKey: this.projectKey,
          status: 1,
          workId: type == 'draft' ? this.workId : null,
        };
        let [onParkData, underParkData] = await Promise.all([this.getOnparkData(apiName, param), this.getUnderparkData(apiName, param)]);
        this.onFiledList = [];
        this.underFiledList = [];
        this.onFloorParkList = onParkData;
        this.underFloorParkList = underParkData;
        //调用formCommon中的initModel方法，以达到清空model准备触发监听中的方法的目的
        this.$nextTick(() => {
          for (let i in this.$refs) {
            if (this.$refs[i].length > 0) {
              this.$refs[i][0].initModel();
            }
          }
          this.initParkData(onParkData, underParkData);
        });
      },
      //地上停车场数据
      async getOnparkData(apiName, data) {
        let param = JSON.parse(JSON.stringify(data));
        param.parkType = 0;
        return new Promise(async (resolve, reject) => {
          let res = await projectInfoApi[apiName](param);
          this.doZeroShow(res);
          resolve(res.rows || []);
        });
      },
      //地下停车场数据
      async getUnderparkData(apiName, data) {
        let param = JSON.parse(JSON.stringify(data));
        param.parkType = 1;
        return new Promise(async (resolve, reject) => {
          let res = await projectInfoApi[apiName](param);
          this.doZeroShow(res);
          resolve(res.rows || []);
        });
      },
      //项目信息
      async getProjectInfo() {
        let res = await projectInfoApi.apiProjectDetail({
          primaryKey: this.projectKey,
        });
        this.model = res;
      },
      //初始停车场化数据
      initParkData(resOn, resUnder) {
        resOn.forEach(item => {
          let onFloorParkFiledListReadonly = JSON.parse(JSON.stringify(onFloorParkFiledList));
          this.initFormReadOnly(onFloorParkFiledListReadonly);
          this.setFiledVal(onFloorParkFiledListReadonly, item);
          this.onFiledList.push(onFloorParkFiledListReadonly);
        });

        resUnder.forEach((item, index) => {
          let underFloorParkFiledListReadonly = JSON.parse(JSON.stringify(underFloorParkFiledList));
          underFloorParkFiledListReadonly.forEach(async field => {
            if (field.bindFieldName == 'functionalPartition') {
              let res = await projectInfoApi.apiParkArea({ spaceKey: item.buildingKey });
              field.optionList = res.rows || [];
            }
          });
          // this.initFormReadOnly(underFloorParkFiledListReadonly);
          this.setFiledVal(underFloorParkFiledListReadonly, item);
          this.underFiledList.push(underFloorParkFiledListReadonly);
        });
      },
      //新增
      addPark(type) {
        this.parkType = type;
        this.infoKey = '';
        this.dialogShow = true;
        this.$nextTick(() => {
          this.$refs.parkForm.clearValidateForm();
        });
        this.fileList = [];
        this.parkImg = '';
      },
      //确认新增
      async confirmAddPark() {
        let model = this.$refs.parkForm.validateForm();
        if (!model) return;
        model.workId = this.workId;
        model.parkType = this.parkType == 'under' ? 1 : 0;
        model.projectKey = this.projectKey;
        model.primaryKey = this.infoKey ? this.infoKey : '';
        model.businessAttachment = this.fileList;
        model.parkImg = this.parkImg;
        let res = this.infoKey ? await projectInfoApi.apiParkEdit(model) : await projectInfoApi.apiParkAdd(model);
        requestTips(res, () => {
          this.getInfo('draft');
          this.dialogShow = false;
        });
      },
      //编辑
      editFn(row, type, refName) {
        //如果连续编辑同一条数据，则不会出发formCommon中的watch，所以手动改数据触发一次
        this.underFloorParkFiledList[0].bindFieldVal = '手动变化以出发watch';
        this.onFloorParkFiledList[0].bindFieldVal = '手动变化以出发watch';
        this.parkType = type;
        this.infoKey = row.primaryKey;
        this.fileList = row.businessAttachment;
        this.parkImg = row.parkImg;
        this.dialogShow = true;
        this.$nextTick(() => {
          //清空校验和formCommon中的model
          this.$refs.parkForm.clearValidateForm();
          let list = type == 'under' ? this.underFloorParkFiledList : this.onFloorParkFiledList;
          this.setFiledVal(list, row);
        });
      },
      //回显
      setFiledVal(list, row) {
        list.forEach(item => {
          for (let i in row) {
            if (i == item.bindFieldName) {
              item.bindFieldVal = row[i];
            }
          }
        });
      },
      //删除
      async deleteFn(data) {
        askDialog('确认删除？', async () => {
          const res = await projectInfoApi.apiParkDelete({ primaryKey: data.primaryKey });
          requestTips(res, () => {
            this.getInfo('draft');
          });
        });
      },
      approveSubmit() {
        askDialog('确认提交？', async () => {
          let data = {
            workType: 3,
            projectKey: this.projectKey,
            workId: this.workId,
          };
          const res = await projectInfoApi.summitAuditAndSuccess(data);
          requestTips(res, () => {
            this.getInfo();
            this.getProjectInfo();
            this.btnStatus = true;
          });
        });
      },
      //提审
      async approveFn() {
        let pathUrl = {
          name: 'arraignment-park',
          query: {
            ...this.$route.query,
            workId: this.workId,
          },
        };
        let { href } = this.$router.resolve(pathUrl);
        window.open(href);
        // askDialog('确认提审？', async () => {
        //   let data = {
        //     workType: 3,
        //     projectKey: this.projectKey,
        //     workId: this.workId,
        //   };
        //   let res = await projectInfoApi.summitAudit(data);
        //   requestTips(res, () => {
        //     this.btnStatus = true;
        //     this.getInfo();
        //   });
        // });
      },
      beforeupload(file) {
        let loading = this.$loading({
          lock: true,
          text: '上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        });
        uploadPhoto(file).then(res => {
          this.parkImg = res.data.rows[0].url;
          loading.close();
        });
      },
      //查看附件
      typeBtnClick(data) {
        if (data.filedName == 'businessAttachment') {
          if (!data.model.businessAttachment || data.model.businessAttachment.length == 0) {
            this.$message.warning('暂无文件');
            return;
          }
          this.fileList = data.model.businessAttachment;
          this.fileDialog = true;
        } else if (data.filedName == 'parkImg') {
          if (!data.model.parkImg) {
            this.$message.warning('暂无图片');
            return;
          }

          this.imgList = [data.model.parkImg];
          this.imgViewerVisible = true;
        }
      },
      closeImgViewer() {
        this.imgViewerVisible = false;
      },
      //上传成功
      handleSuccess(file, fileList) {
        if (file.data.rows && file.data.rows.length > 0) {
          this.fileList.push({
            fileId: file.data.rows[0].key,
            fileUrl: file.data.rows[0].url,
            fileTitle: file.data.rows[0].originalName,
          });
        } else {
          this.fileList = [];
          this.$message.error(file.data.message);
        }
      },
      //下载
      uploadLoad(url) {
        let a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      },
      //按钮状态
      async draftFn() {
        if (this.btnStatus) {
          let res = await projectInfoApi.getWorkId({ projectKey: this.projectKey, workType: 3 }); //workType:1 楼层规划 2 广告 3停车场 4 基础设施
          //1-待审核//2-审核中//3-通过//4-不通过
          if (res.procStatus == 2) {
            this.$message.warning('审批中，无草稿数据');
            return;
          }
          this.workId = res.workId;
          this.btnStatus = !this.btnStatus;
          this.getInfo('draft');
        } else {
          this.getInfo();
          this.btnStatus = !this.btnStatus;
        }
      },
      //处理0的反显
      doZeroShow(res) {
        res.rows.forEach(item => {
          for (let i in item) {
            if (typeof item[i] == 'number' && item[i] == 0) {
              item[i] = String(item[i]);
            }
          }
        });
      },
      async selectChange(data) {
        if (data.filedName == 'buildingKey') {
          let res = await projectInfoApi.apiParkArea({ spaceKey: data.filedVal });
          data.cbList('functionalPartition', res.rows || []);
        }
      },
    },

    components: {
      formCommon,
      uploadFile,
      approvePark,
      'el-image-viewer': () => import('element-ui/packages/image/src/image-viewer'),
    },
  };
</script>
<style scoped lang="scss">
  .park-btn-box {
    position: absolute;
    right: 0;
    bottom: 20px;
  }
  .required::after {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
  }

  .avatar-uploader ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
